﻿using System;
using System.Windows.Input;

namespace MyCalculator
{
    internal class RelayCommond : ICommand
    {
        /// <summary>
        /// 告知命令是否能够执行
        /// </summary>
        readonly Func<bool> _canExecute;
        /// <summary>
        /// 告知命令执行的方法
        /// </summary>
        readonly Action _execute;

        public RelayCommond(Action action, Func<bool> canExecute)
        {
            _execute = action;
            _canExecute = canExecute;
        }

        public bool CanExecute(object parameter)
        {
            if (_canExecute == null)
            {
                return true;
            }
            return _canExecute();
        }

        public void Execute(object parameter)
        {
            _execute();
        }

        public event EventHandler CanExecuteChanged
        {
            add
            {
                if (_canExecute == null)
                {
                    CommandManager.RequerySuggested += value;
                }
            }
            remove
            {
                if (_canExecute == null)
                {
                    CommandManager.RequerySuggested -= value;
                }
            }
        }
    }
}
